#include "Server.h"
#include "Session.h"
#include <functional>
#include <iostream>


Server::Server(boost::asio::io_context& io_context, short port)
:io_context_(io_context),
acceptor_(io_context_, tcp::endpoint(tcp::v4(), port)),
port_(port)
{
    
}
void Server::StartAccept()
{
    
    auto session = std::make_shared<Session>(io_context_,this);
    acceptor_.async_accept(session->GetSocket(),
        std::bind(&Server::handleAccept,this,std::placeholders::_1,session));
    
}
Server::~Server()
{

}

void Server::handleAccept(const boost::system::error_code& ec,std::shared_ptr<Session> session)
{
    if (ec)
    {
        std::cout<<"handleAccept error error value: "<<ec.value()<<" message: "<<ec.message()<<std::endl;
        return;
    }
    sessions_[session->GetUuid()] = session;
    std::cout<<"handleAccept success"<<std::endl;
    session->Start();
    StartAccept();

}

void Server::ClearSession(std::string uuid)
{
    if(sessions_.find(uuid) == sessions_.end())
    {
        return;
    }
    sessions_.erase(uuid);
}